<template>
  <div>
    <div class="gva-search-box">
      <el-form ref="elSearchFormRef"
               :inline="true"
               :model="searchInfo"
               class="demo-form-inline"
               :rules="searchRule"
               @keyup.enter="onSubmit">
        <el-form-item label="创建日期"
                      prop="createdAt">
          <template #label>
            <span>
              创建日期
              <el-tooltip content="搜索范围是开始日期（包含）至结束日期（不包含）">
                <el-icon>
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
            </span>
          </template>
          <el-date-picker v-model="searchInfo.startCreatedAt"
                          type="datetime"
                          placeholder="开始日期"
                          :disabled-date="time=> searchInfo.endCreatedAt ? time.getTime() > searchInfo.endCreatedAt.getTime() : false"></el-date-picker>
          —
          <el-date-picker v-model="searchInfo.endCreatedAt"
                          type="datetime"
                          placeholder="结束日期"
                          :disabled-date="time=> searchInfo.startCreatedAt ? time.getTime() < searchInfo.startCreatedAt.getTime() : false"></el-date-picker>
        </el-form-item>
        <el-form-item label="问卷名称"
                      prop="name">
          <el-input v-model="searchInfo.name"
                    placeholder="搜索条件" />

        </el-form-item>
        <el-form-item label="问卷uuid"
                      prop="uuid">
          <el-input v-model="searchInfo.uuid"
                    placeholder="搜索条件" />

        </el-form-item>
        <el-form-item label="截至日期"
                      prop="endTime">

          <template #label>
            <span>
              截至日期
              <el-tooltip content="搜索范围是开始日期（包含）至结束日期（不包含）">
                <el-icon>
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
            </span>
          </template>
          <el-date-picker v-model="searchInfo.startEndTime"
                          type="datetime"
                          placeholder="开始日期"
                          :disabled-date="time=> searchInfo.endEndTime ? time.getTime() > searchInfo.endEndTime.getTime() : false"></el-date-picker>
          —
          <el-date-picker v-model="searchInfo.endEndTime"
                          type="datetime"
                          placeholder="结束日期"
                          :disabled-date="time=> searchInfo.startEndTime ? time.getTime() < searchInfo.startEndTime.getTime() : false"></el-date-picker>

        </el-form-item>
        <el-form-item>
          <el-button type="primary"
                     icon="search"
                     @click="onSubmit">查询</el-button>
          <el-button icon="refresh"
                     @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary"
                   icon="plus"
                   @click="openDialog">新增</el-button>
        <el-popover v-model:visible="deleteVisible"
                    :disabled="!multipleSelection.length"
                    placement="top"
                    width="160">
          <p>确定要删除吗？</p>
          <div style="text-align: right; margin-top: 8px;">
            <el-button type="primary"
                       link
                       @click="deleteVisible = false">取消</el-button>
            <el-button type="primary"
                       @click="onDelete">确定</el-button>
          </div>
          <template #reference>
            <el-button icon="delete"
                       style="margin-left: 10px;"
                       :disabled="!multipleSelection.length"
                       @click="deleteVisible = true">删除</el-button>
          </template>
        </el-popover>
      </div>
      <el-table ref="multipleTable"
                style="width: 100%"
                tooltip-effect="dark"
                :data="tableData"
                row-key="ID"
                :row-class-name="tableRowClassName"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection"
                         width="55" />
        <el-table-column label="序号"
                         type="index"
                         width="100px"
                         align="center" />
        <el-table-column align="left"
                         label="问卷名称"
                         prop="name"
                         width="200" />
        <el-table-column align="left"
                         label="uuid"
                         prop="uuid"
                         width="150" />
        <el-table-column align="left"
                         label="日期"
                         width="180">
          <template #default="scope">{{ formatDate(scope.row.CreatedAt) }}</template>

        </el-table-column>
        <el-table-column align="left"
                         label="截至日期"
                         width="180">
          <template #default="scope">{{ formatDate(scope.row.endTime) }}</template>
        </el-table-column>

        <el-table-column align="left"
                         label="收集数"
                         prop="number"
                         width="150" />
        <el-table-column align="left"
                         label="问卷人数上限"
                         prop="endNumber"
                         width="150">
          <template #default="scope">
            <div v-if="scope.row.endNumber!=0">
              {{ scope.row.endNumber }}
            </div>
            <div v-if="scope.row.endNumber==0">
              无限制
            </div>
          </template>
        </el-table-column>
        <el-table-column align="left"
                         label="状态"
                         width="150">
          <template #default="scope">
            <el-switch v-model="scope.row.st"
                       @click="changeSt(scope.row)"
                       v-stopReClick
                       active-text="开启"
                       :active-value="1"
                       inactive-text="关闭"
                       :inactive-value="2" />
          </template>
        </el-table-column>
        <el-table-column align="left"
                         label="操作">
          <template #default="scope">
            <el-button type="primary"
                       link
                       class="table-button"
                       @click="getDetails(scope.row)">
              <el-icon style="margin-right: 5px">
                <InfoFilled />
              </el-icon>
              查看详情
            </el-button>
            <el-button type="primary"
                       link
                       icon="edit"
                       class="table-button"
                       @click="updateQuestionnaireFunc(scope.row)">变更</el-button>

            <el-button type="primary"
                       link
                       icon="delete"
                       @click="deleteRow(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination layout="total, sizes, prev, pager, next, jumper"
                       :current-page="page"
                       :page-size="pageSize"
                       :page-sizes="[10, 30, 50, 100]"
                       :total="total"
                       @current-change="handleCurrentChange"
                       @size-change="handleSizeChange" />
      </div>
    </div>
    <el-dialog v-model="dialogFormVisible"
               :before-close="closeDialog"
               :title="type==='create'?'添加':'修改'"
               destroy-on-close>
      <el-scrollbar height="500px">
        <el-form :model="formData"
                 label-position="right"
                 ref="elFormRef"
                 :rules="rule"
                 label-width="100px">
          <el-form-item label="问卷类型:"
                        prop="name">
            <el-select v-model="formData.questionnaireType"
                       v-if="type=='create'"
                       class="m-2"
                       placeholder="Select">
              <el-option :key="1"
                         label="企业评分"
                         :value="1" />
              <el-option :key="2"
                         label="制作问卷"
                         :value="2" />
            </el-select>
            <el-select v-model="formData.questionnaireType"
                       disabled
                       v-if="type=='update'"
                       class="m-2"
                       placeholder="Select">
              <el-option :key="1"
                         label="企业评分"
                         :value="1" />
              <el-option :key="2"
                         label="制作问卷"
                         :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="问卷名称:"
                        prop="name">
            <el-input v-model="formData.name"
                      :clearable="true"
                      placeholder="请输入问卷名称" />
          </el-form-item>
          <el-form-item label="截至日期:"
                        prop="endTime">
            <el-date-picker v-model="formData.endTime"
                            type="date"
                            style="width:100%"
                            placeholder="选择日期"
                            :clearable="true" />
          </el-form-item>
          <el-form-item label="人数上限:"
                        prop="endNumber">
            <el-input v-model.number="formData.endNumber"
                      :clearable="true"
                      placeholder="请输入问卷人数上限" />
          </el-form-item>
          <el-form-item label="问卷状态:"
                        prop="st">
            <el-switch v-model="formData.st"
                       active-text="开启"
                       :active-value="1"
                       inactive-text="关闭"
                       :inactive-value="2" />
          </el-form-item>
          <el-form-item label="分数设置:"
                        v-if="(formData.questionnaireType==1&&formData.number==0&&formData.st!=1)||type=='create'"
                        prop="markListInfo">
            <div v-for="tag, index in markInfoList"
                 :key="index">
              <el-input v-if="editable[index]"
                        v-model="markInfoList[index].name"
                        placeholder="请输入分数"
                        @blur="handleEditableInputConfirm(tag, index)"
                        maxlength="20"
                        show-word-limit>
              </el-input>
              <el-tag v-else
                      @click="showEditTagInput(index)"
                      closable
                      :disable-transitions="false"
                      @close="handleClose(tag, index)">
                {{ tag.name }}
              </el-tag>
            </div>
            <div>
              <el-input class="input-new-tag"
                        v-if="inputVisible"
                        v-model="inputValue"
                        oninput="value=value.replace(/[^0-9.]/g,'')"
                        ref="saveTagInput"
                        @keyup.enter="handleInputConfirm"
                        @blur="handleInputConfirm"
                        maxlength="10"
                        show-word-limit>
              </el-input>
              <el-button v-else
                         class="button-new-tag"
                         @click="showInput">+ 新增分数</el-button>
            </div>
          </el-form-item>
          <el-form-item label="分数设置:"
                        v-if="formData.questionnaireType==1&&formData.number!=0&&formData.st==1&&type=='update'"
                        prop="markListInfo">'
            <div v-for="tag, index in markInfoList"
                 :key="index">
              <el-tag>
                {{ tag.name }}
              </el-tag>
            </div>

          </el-form-item>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary"
                     v-stopReClick
                     @click="enterDialog">确 定</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script  setup >
import {
  createQuestionnaire,
  deleteQuestionnaire,
  deleteQuestionnaireByIds,
  updateQuestionnaire,
  findQuestionnaire,
  getQuestionnaireList,
} from '@/api/questionnaire'
import moment from 'moment'
// 全量引入格式化工具 请按需保留
import {
  getDictFunc,
  formatDate,
  formatBoolean,
  filterDict,
  ReturnArrImg,
} from '@/utils/format'
import { uniqueJsonArrByField } from '@/utils/json'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive, nextTick, toRaw } from 'vue'
import { useRoute, useRouter } from "vue-router"
defineOptions({
  name: 'Questionnaire',
})

// 自动化生成的字典（可能为空）以及字段
const formData = ref({
  name: '',
  questionnaireType: null,
  endTime: null,
  endNumber: 0,
  markList: [],
  markListInfo: [],
  uuid: '',
})
const markInfoList = ref([])
// 验证规则
const rule = reactive({
  name: [
    {
      required: true,
      message: '请输入问卷名称',
      trigger: ['input', 'blur'],
    },
    {
      whitespace: true,
      message: '不能只输入空格',
      trigger: ['input', 'blur'],
    },
  ],
  endNumber: [
    { required: true, message: '请输入数字', trigger: 'blur' },
    { pattern: /^[0-9]*$/, message: '只能输入数字', trigger: 'blur' },
  ],
  questionnaireType: [
    { required: true, message: '请选择问卷类型', trigger: 'blur' },
    { pattern: /^[0-9]*$/, message: '请选择问卷类型', trigger: 'blur' },
  ],
})

const searchRule = reactive({
  createdAt: [
    {
      validator: (rule, value, callback) => {
        if (searchInfo.value.startCreatedAt && !searchInfo.value.endCreatedAt) {
          callback(new Error('请填写结束日期'))
        } else if (
          !searchInfo.value.startCreatedAt &&
          searchInfo.value.endCreatedAt
        ) {
          callback(new Error('请填写开始日期'))
        } else if (
          searchInfo.value.startCreatedAt &&
          searchInfo.value.endCreatedAt &&
          (searchInfo.value.startCreatedAt.getTime() ===
            searchInfo.value.endCreatedAt.getTime() ||
            searchInfo.value.startCreatedAt.getTime() >
            searchInfo.value.endCreatedAt.getTime())
        ) {
          callback(new Error('开始日期应当早于结束日期'))
        } else {
          callback()
        }
      },
      trigger: 'change',
    },
  ],
  endTime: [
    {
      validator: (rule, value, callback) => {
        if (searchInfo.value.startEndTime && !searchInfo.value.endEndTime) {
          callback(new Error('请填写结束日期'))
        } else if (
          !searchInfo.value.startEndTime &&
          searchInfo.value.endEndTime
        ) {
          callback(new Error('请填写开始日期'))
        } else if (
          searchInfo.value.startEndTime &&
          searchInfo.value.endEndTime &&
          (searchInfo.value.startEndTime.getTime() ===
            searchInfo.value.endEndTime.getTime() ||
            searchInfo.value.startEndTime.getTime() >
            searchInfo.value.endEndTime.getTime())
        ) {
          callback(new Error('开始日期应当早于结束日期'))
        } else {
          callback()
        }
      },
      trigger: 'change',
    },
  ],
})

const elFormRef = ref()
const elSearchFormRef = ref()

// =========== 表格控制部分 ===========
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})

// 重置
const onReset = () => {
  searchInfo.value = {}
  getTableData()
}

// 搜索
const onSubmit = () => {
  elSearchFormRef.value?.validate(async (valid) => {
    if (!valid) return
    page.value = 1
    pageSize.value = 10
    getTableData()
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

//
const tableRowClassName = (row) => {
  row = toRaw(row).row
  if (row.st == 1 && moment(row.endTime).isAfter(new Date())) {
    return 'progress-row'
  }
  if (row.st == 1 && moment(row.endTime).isBefore(new Date())) {
    return 'success-row '
  }
  if (row.st == 1 && row.endNumber != 0 && row.endNumber == row.number) {
    return 'success-row '
  }
  if (row.st == 0 && row.number != 0) {
    return 'success-row '
  }
  return ''
}

const inputValue = ref('')
const inputVisible = ref(false)
const saveTagInput = ref()
const editable = ref([])
const inputRef = ref()
const handleEditableInputConfirm = (item, index) => {
  if (item.name) {
    editable.value[index] = false
    markInfoList.value = uniqueJsonArrByField(markInfoList.value, "name")
    markInfoList.value.sort(function (a, b) {
      return a.name > b.name ? 1 : -1
    });
  } else {
    ElMessage.error({ message: "请输入分数信息", type: "info" });
  }
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    saveTagInput.value.input.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value) {
    const str = {
      name: inputValue.value,
      value: markInfoList.value.length + 1,
    }
    markInfoList.value.push(str)
    markInfoList.value = uniqueJsonArrByField(markInfoList.value, "name")
    markInfoList.value.sort(function (a, b) {
      return a.name - b.name 
    });
    formData.value.markList.push(str.name)
    //去重
    formData.value.markList = [...new Set(formData.value.markList)]
    formData.value.markListInfo = formData.value.markList.join()
  }

  inputVisible.value = false
  inputValue.value = ''
}

//编辑标签信息 input显示
const showEditTagInput = (index) => {
  editable.value[index] = true
  nextTick((_) => {
    (inputRef.value && inputRef.value.input) ? inputRef.value.input.focus() : null;
  });
}

//删除条目
const handleClose = (tag, index) => {
  markInfoList.value.splice(index, 1);
  formData.value.markList.splice(index, 1)
  formData.value.markListInfo = formData.value.markList.join()
}

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// 查询
const getTableData = async () => {
  const table = await getQuestionnaireList({
    page: page.value,
    pageSize: pageSize.value,
    ...searchInfo.value,
  })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

getTableData()

// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async () => { }

// 获取需要的字典 可能为空 按需保留
setOptions()

// 多选数据
const multipleSelection = ref([])
// 多选
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 删除行
const deleteRow = (row) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteQuestionnaireFunc(row)
  })
}

// 批量删除控制标记
const deleteVisible = ref(false)

// 多选删除
const onDelete = async () => {
  const ids = []
  if (multipleSelection.value.length === 0) {
    ElMessage({
      type: 'warning',
      message: '请选择要删除的数据',
    })
    return
  }
  multipleSelection.value &&
    multipleSelection.value.map((item) => {
      ids.push(item.ID)
    })
  const res = await deleteQuestionnaireByIds({ ids })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    if (tableData.value.length === ids.length && page.value > 1) {
      page.value--
    }
    deleteVisible.value = false
    getTableData()
  }
}

// 行为控制标记（弹窗内部需要增还是改）
const type = ref('')

// 更新行
const updateQuestionnaireFunc = async (row) => {
  const res = await findQuestionnaire({ ID: row.ID })
  type.value = 'update'
  if (res.code === 0) {
    formData.value = res.data.requestionnaire
    formData.value.markList = formData.value.markListInfo.split(",")
    for (var i = 0; i < formData.value.markList.length; i++) {
      markInfoList.value.push({ name: formData.value.markList[i] })
    }
    dialogFormVisible.value = true
  }
}

// 删除行
const deleteQuestionnaireFunc = async (row) => {
  const res = await deleteQuestionnaire({ ID: row.ID })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    if (tableData.value.length === 1 && page.value > 1) {
      page.value--
    }
    getTableData()
  }
}

// 弹窗控制标记
const dialogFormVisible = ref(false)



const router = useRouter()
// 打开详情
const getDetails = async (row) => {
  router.push({
    path: '/questionnaireInfo/detailedInfo',
    query: {
      uuid: row.uuid
    }
  })
}


// 打开弹窗
const openDialog = () => {
  type.value = 'create'
  dialogFormVisible.value = true
}

// 关闭弹窗
const closeDialog = () => {
  dialogFormVisible.value = false
  formData.value = {
    name: '',
    st: 0,
    questionnaireType: null,
    endTime: null,
    endNumber: 0,
    markList: [],
    markListInfo: '',
    uuid: '',
  }
  markInfoList.value = []
}
// 弹窗确定
const enterDialog = async () => {
  elFormRef.value?.validate(async (valid) => {
    if (!valid) return
    if (formData.value.questionnaireType == 1 && formData.value.markList.length == 0) {
      ElMessage({
        showClose: true,
        message: '请添加分数选项',
        type: 'error',
      })
      return
    }
    let res
    switch (type.value) {
      case 'create':
        res = await createQuestionnaire(formData.value)
        break
      case 'update':
        res = await updateQuestionnaire(formData.value)
        break
      default:
        res = await createQuestionnaire(formData.value)
        break
    }
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '创建/更改成功',
      })
      closeDialog()
      getTableData()
    }
  })
}
//更换状态
const changeSt = async (row) => {
  let res = await updateQuestionnaire(row)
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '状态更新成功',
    })
  } else {
    if (row.st == 1) {
      row.st = 2
    } else {
      row.st = 1
    }
  }
}
</script>

<style>
.el-table .success-row {
  background: #f0f9eb;
}
.el-table .warning-row {
  background: #fef0f0;
}
.el-table .progress-row {
  background: #ecf5ff !important;
}
</style>
